package book.daoimp;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.hibernate.SessionFactory;

import book.dao.borrowDAO;
import book.dto.book;
import book.dto.borrow;

public class borrowDAOImpl implements borrowDAO {

	private SessionFactory sessionFactory;
	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	public List query(String snumber) {
		List<book> l = new ArrayList();
		List list =sessionFactory.getCurrentSession()
				.createQuery("from borrow where snumber='" + snumber+"'").list();
		if(list.size()!=0){
			for (int j = 0; j < list.size(); j++) {
				borrow b=(borrow)list.get(j);
				String isbn=b.getIsbn();
			book bo = (book) sessionFactory.getCurrentSession()
					.createQuery("from book where isbn='" +isbn+ "'")
					.list().get(0);
			l.add(j, bo);
			}
		    }else{
				l=null;
			}
		return l;
	}

	public void add(borrow borrow) {
		Date date = new Date();
		String nowTime = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss").format(date);
		Timestamp g = Timestamp.valueOf(nowTime);
		borrow.setBtime(g);
		sessionFactory.getCurrentSession().save(borrow);
	}

	public void delete(String isbn) {
		borrow b = (borrow) sessionFactory.getCurrentSession()
				.createQuery("from borrow where isbn='" + isbn+"'").list().get(0);
		sessionFactory.getCurrentSession().delete(b);
	}

}
